<template>
	<view class="container">
		<!-- 顶部导航 -->
		<view class="header">
			<view class="back-icon" @click="goBack">
				<u-icon name="arrow-left" size="30"></u-icon>
			</view>
			<view class="title">收货地址</view>
			<view class="right-icon">
				<u-icon name="more-dot-fill" size="30"></u-icon>
			</view>
		</view>
		
		<!-- 地址列表 -->
		<view class="address-list" v-if="addressList.length > 0">
			<view
				class="address-item"
				v-for="item in addressList"
				:key="item.addressId"
			>
				<view class="address-info" @click="selectAddress(item)">
					<view class="user-info">
						<text class="name">{{item.addressName}}</text>
						<text class="phone">{{item.addressPhone}}</text>
					</view>
					<view class="address-detail">{{item.addressInfo}} {{item.addressCommunity}}</view>
					<view class="default-tag" @click.stop="setDefaultAddress(item)">
						<u-icon
							:name="item.addressDefault == 1 ? 'checkmark-circle-fill' : 'checkmark-circle'"
							:color="item.addressDefault == 1 ? '#67c23a' : '#999'"
							size="22"
						></u-icon>
						<text style="margin-left: 6rpx;">设为默认</text>
					</view>
				</view>
				<view class="action-btns">
					<view class="edit-btn" @click.stop="editAddress(item)">编辑</view>
					<u-icon
						name="trash"
						color="#999"
						size="28"
						@click="deleteAddress(item)"
						class="delete-btn"
					></u-icon>
				</view>
			</view>
		</view>
		
		<!-- 空状态 -->
		<view class="empty-state" v-else>
			<image class="empty-icon" src="http://121.36.197.175:19000/test/location-empty.png" mode="aspectFit"></image>
			<text class="empty-text">暂无收货地址</text>
		</view>
		
		<!-- 底部按钮 -->
		<view class="bottom-btns">
			<button class="btn add-btn" @click="goToAddAddress">+ 新增收货地址</button>
			<button class="btn wechat-btn" @click="getWechatAddress">+ 微信地址</button>
		</view>
	</view>
</template>

<script>
import request from '@/util/request.js'

export default {
	data() {
		return {
			addressList: [],
			swipeOptions: [
				{
					text: '编辑',
					style: {
						backgroundColor: '#3c9cff',
						color: '#fff'
					}
				},
				{
					text: '删除',
					style: {
						backgroundColor: '#f56c6c',
						color: '#fff'
					}
				}
			]
		}
	},
	onLoad() {
		this.getAddressList()
		
		// 监听刷新地址列表事件
		uni.$on('refreshAddressList', () => {
			this.getAddressList()
		})
	},
	onShow() {
		
		this.getAddressList()
	},
	onUnload() {
		
		uni.$off('refreshAddressList')
	},
	methods: {
		goBack() {
			uni.navigateBack()
		},
		async getAddressList() {
			try {
				const userInfo = uni.getStorageSync('userInfo')
				const res = await request({
					url: `/user-service/address/list?userId=${userInfo.userId}`,
					method: 'GET'
				})
				
				this.addressList = res.data.list || []
				
				
			} catch (err) {
				
				this.addressList = []

			}
		},
		selectAddress(item) {
			// 选择地址
			uni.$emit('addressSelected', item)
			// 将选择的地址存储到本地，以便确认订单页面获取
			uni.setStorageSync('selectedAddress', item)
			uni.navigateBack()
		},
		editAddress(item) {
			uni.setStorageSync('editAddress', item)
			uni.navigateTo({
				url: `/pages/address/edit-address?id=${item.addressId}`
			})
		},
		goToAddAddress() {
			uni.navigateTo({
				url: '/pages/address/add-address'
			})
		},
		getWechatAddress() {
			// 调用微信收货地址API
			uni.chooseAddress({
				success: async (res) => {
					console.log('微信地址:', res)
					// 处理微信返回的地址信息
					const userInfo = uni.getStorageSync('userInfo')
					if (!userInfo || !userInfo.userId) {
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						})
						return
					}
					
					try {
						// 构建地址对象
						const addressData = {
							userId: userInfo.userId,
							addressName: res.userName,
							addressPhone: res.telNumber,
							addressInfo: `${res.provinceName}${res.cityName}${res.countyName}${res.detailInfo}`,
							addressCommunity: '',
							addressDefault: res.isDefault == 1 ? 1 : 2
						}
						
						// 调用添加地址接口
						const result = await request({
							url: '/user-service/address/add',
							method: 'POST',
							data: addressData
						})
						
						uni.showToast({
							title: '添加成功',
							icon: 'success'
						})
						
						// 刷新地址列表
						this.getAddressList()
					} catch (err) {
						console.error('添加微信地址失败:', err)
					}
				},
				fail: (err) => {
					console.error('获取微信地址失败:', err)
					if (err.errMsg && err.errMsg.indexOf('auth deny') > -1) {
						uni.showToast({
							title: '您已拒绝授权获取地址',
							icon: 'none'
						})
					}
				}
			})
		},
		async deleteAddress(item) {
			console.log('删除的item:', item);
			uni.showModal({
				title: '提示',
				content: '确定要删除该地址吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							await request({
								url: `/user-service/address/delete?id=${item.addressId}`,
								method: 'DELETE',
								header: {
        'Content-Type': 'application/json'
    }
							
							
							})
							uni.showToast({ title: '删除成功', icon: 'success' })
							this.getAddressList()
						} catch (err) {}
					}
				}
			})
		},
		async setDefaultAddress(item) {
			if (item.addressDefault == 1) return; // 已经是默认就不处理
			try {
				const userInfo = uni.getStorageSync('userInfo')
				await request({
					url: `/user-service/address/setDefault?userId=${userInfo.userId}&addressId=${item.addressId}`,
					method: 'PUT'
				});
				uni.showToast({ title: '设置成功', icon: 'success' });
				this.getAddressList(); // 重新拉取列表
			} catch (err) {
				uni.showToast({ title: '设置失败', icon: 'none' });
			}
		}
	}
}
</script>

<style lang="scss">
.container {
	min-height: 100vh;
	background-color: #f8f8f8;
	position: relative;
	padding-bottom: 120rpx;
}

.header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 88rpx;
	padding: 0 30rpx;
	background-color: #ffffff;
	position: relative;
	
	.back-icon {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
	}
	
	.title {
		font-size: 32rpx;
		font-weight: 500;
		color: #333;
	}
	
	.right-icon {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: flex-end;
	}
}

.address-list {
	padding: 20rpx;
	
	.address-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		background-color: #ffffff;
		border-radius: 12rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		position: relative;
		
		.address-info {
			flex: 1;
			padding-right: 120rpx;
			
			.user-info {
				display: flex;
				align-items: center;
				margin-bottom: 10rpx;
				
				.name {
					font-size: 32rpx;
					font-weight: 500;
					color: #333;
					margin-right: 20rpx;
				}
				
				.phone {
					font-size: 28rpx;
					color: #666;
				}
			}
			
			.address-detail {
				font-size: 28rpx;
				color: #666;
				line-height: 1.5;
			}
			
			.default-tag {
				display: flex;
				align-items: center;
				cursor: pointer;
				margin-top: 10rpx;
				
				text {
					font-size: 22rpx;
					color: #67c23a;
				}
			}
		}
		.action-btns {
			position: absolute;
			right: 30rpx;
			top: 50%;
			transform: translateY(-50%);
			display: flex;
			align-items: center;
			.edit-btn {
				color: #409EFF;
				font-size: 28rpx;
				margin-right: 30rpx;
				cursor: pointer;
			}
			.delete-btn {
				color: #999;
				font-size: 36rpx;
				cursor: pointer;
			}
		}
	}
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;
	
	.empty-icon {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 30rpx;
	}
	
	.empty-text {
		font-size: 28rpx;
		color: #999;
	}
}

.bottom-btns {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	display: flex;
	padding: 20rpx;
	background-color: #ffffff;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	
	.btn {
		flex: 1;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		font-size: 28rpx;
		border-radius: 40rpx;
		margin: 0 10rpx;
	}
	
	.add-btn {
		background-color: #67c23a;
		color: #ffffff;
	}
	
	.wechat-btn {
		background-color: #ffffff;
		color: #67c23a;
		border: 1px solid #67c23a;
	}
}
</style>